package cn.demo.controller;

import cn.demo.Util.AgeByBirthday;
import cn.demo.Util.Page;
import cn.demo.Util.Result;
import cn.demo.entity.UserInfo;
import cn.demo.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

/**
 * @Author weizhongli
 * @Date 2020/3/22
 * @Version v1.0
 * @Description 用户管理控制
 */
@Controller
public class UserInfoController {

    //依赖注入service
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    private FileInputStream stream;

    public FileInputStream getStream() {
        return stream;
    }

    public void setStream(FileInputStream stream) {
        this.stream = stream;
    }

    /*
* 获取当前用户登陆的用户名
* */
    @RequestMapping("getUsername")
    @ResponseBody
    public Result getUsername(HttpServletRequest request) {
        try {
            //Springecurity框架的上下文中获取认证对象
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            //认证对象获取User对象
            User user = (User) authentication.getPrincipal();
            //从User对象 获取用户名
            String username = user.getUsername();
            UserInfo byUsername = userInfoService.findByUsername(username);
            if (byUsername.getRole().getKeyword().equals("Ordinary users")){
                request.getSession().setAttribute("keyword","普通员工   ");
            }else if (byUsername.getRole().getKeyword().equals("administrators")){
                request.getSession().setAttribute("keyword","管理员    ");
            }else {
                request.getSession().setAttribute("keyword","经理 ");
            }
            request.getSession().setAttribute("userCode",username);
            request.getSession().setAttribute("login",byUsername.getUserName());
            String userNameKeyWord="";
            if (byUsername.getRole().getKeyword().equals("Ordinary users")){
                userNameKeyWord="普通员工    "+byUsername.getUserName();
            }else if (byUsername.getRole().getKeyword().equals("administrators")){
                userNameKeyWord="管理员    "+byUsername.getUserName();
            }else {
                userNameKeyWord="经理    "+byUsername.getUserName();
            }
            //返回获取的用户名
            return new Result(true, "ACTION_SUCCESS", userNameKeyWord);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "ACTION_FAIL");
        }
    }
   /* @RequestMapping("/sec/isLogin")
    @ResponseBody
    public Result isLogin(String username, String password, HttpServletRequest request, HttpSession session) {
        try {
            UserInfo userInfo = new UserInfo();
            userInfo.setUserCode(username);
            userInfo.setUserPassword(password);
            UserInfo login = userInfoService.Login(userInfo);
            if (login != null && login.getUserName() != null) {
                session.setAttribute("userCode", userInfo.getUserCode());
                request.getSession().setAttribute("login", login.getUserName());
                return new Result(false, "登录成功", "1");
            } else {
                return new Result(false, "登录失败", "0");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "登录失败", "0");
        }
    }*/

    @RequestMapping("/loginout")
    public String loginout(HttpServletRequest request) {
        Enumeration em = request.getSession().getAttributeNames();
        while (em.hasMoreElements()) {
            request.getSession().removeAttribute(em.nextElement().toString());
        }
        return "login";
    }

    /*让用户看到该视图*/
    @RequestMapping("/showUserList")
    public String showUserList() {
        return "userList";
    }


    /*
    * 分页展示
    * */
    //告诉服务器，return后面的内容作为响应流直接输出  对象直接转json
    @ResponseBody
    @RequestMapping("/userInfo")
    public Result userInfo(String userName, @RequestParam(defaultValue = "1") int PageIndex, @RequestParam(defaultValue = "2") int PageSize) throws Exception {
        try {
            Page page = userInfoService.userList(userName, PageIndex, PageSize);
            return new Result(true, "分页展示成功", page);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "分页展示失败");
        }
    }

    @ResponseBody
    @RequestMapping("/insertUser")
    public Result insertUser(UserInfo userInfo) {
        try {
            String userPassword = userInfo.getUserPassword();
            userPassword  = passwordEncoder.encode(userPassword);
            userInfo.setUserPassword(userPassword);
            int i = userInfoService.insertUser(userInfo);
            return new Result(true, "添加成功", i);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "添加失败");
        }

    }

    @RequestMapping("/updateuser")
    public String updateuser(int id, HttpServletRequest request) {
        UserInfo userInfo = userInfoService.chuanuser(id);
        SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = myFormat.format(userInfo.getBirthday());
        request.setAttribute("format", format);
        request.setAttribute("userInfo", userInfo);
        return "userUpdate";
    }

    @ResponseBody
    @RequestMapping("/userupdate")
    public Result userupdate(UserInfo userInfo, HttpServletRequest request) {
        try {
            int updateuser = userInfoService.updateuser(userInfo);
            return new Result(true, "修改成功", updateuser);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "修改失败");
        }
    }

    @ResponseBody
    @RequestMapping("/deleteuser")
    public void deleteuser(String str, HttpServletRequest request, HttpServletResponse response) throws Exception {
        PrintWriter out = response.getWriter();
        String[] ids = str.split(",");
        int deleteuser = 0;
        for (int i = 0; i < ids.length; i++) {
            deleteuser = userInfoService.deleteuser(Integer.parseInt(ids[i].trim()));
        }
        response.getWriter().write("true");
    }

    @RequestMapping("/downloadFile")
    @ResponseBody
    public Result download(HttpServletRequest request,String username) throws Exception {
        List<UserInfo> list = userInfoService.selectUser();
        for (UserInfo item : list) {
            Date birthday = item.getBirthday();
            SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");
            String format = myFormat.format(birthday);
            int age = AgeByBirthday.getagee(format);
            item.setAge(age);
        }
        request.getSession().setAttribute("list",list);
        return new Result(true,"导出成功","exoll");
    }


    /*
    * 展示用户
    * */
    @ResponseBody
    @RequestMapping("/myecharts")
    public Result selecteacharts() throws Exception {
        try {
            List<UserInfo> list = userInfoService.selectUser();
            for (UserInfo item : list) {
                Date birthday = item.getBirthday();
                SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");
                String format = myFormat.format(birthday);
                int age = AgeByBirthday.getagee(format);
                item.setAge(age);
            }
            return new Result(true, "展示成功", list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "展示失败");
        }
    }

}
